package wang.app.demo.api.login;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import wang.app.demo.api.entity.User;
import wang.app.demo.api.user.UserService;
import wang.app.demo.api.entity.BaseResponse;
import wang.app.demo.entity.ResponseEntity;
import wang.app.demo.jwt.JwtUtil;

/**
 * @Author dj.wang
 * @Date 2020/6/19 22:34
 * @Version V1.0
 */
@RestController
public class LoginController
{
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    UserService userService;

    @RequestMapping("/login")
    public BaseResponse login(@RequestParam("username") String username,
                              @RequestParam("password") String password)
    {

        User user = userService.getUserByName(username);
        if (user == null)
        {
            return BaseResponse.fail("没有这个用户");
        }

        // 密码验证
        if (!user.getPassword().equals("pass" + user.getId()))
        {
            return BaseResponse.fail("密码错误");
        }

        String token = JwtUtil.sign(username, user.getPassword(), 100000);
        return new BaseResponse(0, "Login success", token);
    }

    @RequiresRoles("admin")
    @RequiresPermissions("add")
    @RequestMapping("/index")
    public String index()
    {
        return "index!";
    }

    @RequestMapping(path = "/unauthorized")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseEntity unauthorized()
    {
        return new ResponseEntity(1, "Unauthorized", null);
    }
}
